package com.luo.common.base;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.util.StopWatch;

/**
 * 消费者父类：时间记录与防重复消费.
 *
 * @author Breggor
 * @date 2020/3/7 13:55
 */
@Slf4j
public abstract class BaseConsumer<T> {

    //@Autowired
    //private RedisOps redisOps;

    /**
     * 消息处理.
     *
     * @param msg msg
     */
    public void onMessage(final T msg) {
        if (msg == null) {
            log.error("[MQ空事件]");
            return;
        }

        // MQ消息是否重复消费
        //if (redisOps.setIfAbsent(getKey(msg), Integer.valueOf(1), Integer.valueOf(1), TimeUnit.HOURS)) {
            try {
                StopWatch sw = new StopWatch("MQ消费记录");
                sw.start("MQ处理开始");

                doProcess(msg);

                sw.stop();
                log.info(sw.prettyPrint());
            } catch (Exception e) {
                log.error("[MQ处理异常]--{}", ExceptionUtils.getStackTrace(e));
                //redisOps.deleteObject(getKey(msg));
                throw e;
            }
        //} else {
            //log.info("[MQ消息-已处理]--{}", msg);
        //}
    }

    /**
     * 获取key.
     *
     * @param msg msg
     * @return String
     */
    protected abstract String getKey(T msg);

    /**
     * 处理消息.
     *
     * @param msg msg
     */
    protected abstract void doProcess(T msg);

}
